define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'hr/attendance/index' + location.search,
                    table: 'hr_attendance',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('ID'), sortable: true},
                        {field: 'user_name', title: __('员工姓名')},
                        {field: 'attendance_date', title: __('考勤日期'), sortable: true},
                        {field: 'clock_in_time_text', title: __('上班时间')},
                        {field: 'clock_in_address', title: __('上班地点'), formatter: function(value) {
                            return value ? value.substr(0, 30) + '...' : '';
                        }},
                        {field: 'clock_out_time_text', title: __('下班时间')},
                        {field: 'work_hours', title: __('工作时长（小时）')},
                        {field: 'status_text', title: __('状态'), formatter: function(value, row) {
                            var colorMap = {
                                '正常': 'success',
                                '迟到': 'danger',
                                '早退': 'warning',
                                '旷工': 'default',
                                '请假': 'info',
                                '加班': 'primary'
                            };
                            var color = colorMap[value] || 'default';
                            return '<span class="label label-' + color + '">' + value + '</span>';
                        }},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate, buttons: [
                            {
                                name: 'detail',
                                text: __('详情'),
                                classname: 'btn btn-xs btn-info btn-dialog',
                                icon: 'fa fa-list',
                                url: 'hr/attendance/detail',
                                extend: 'data-area=\'["90%", "90%"]\''
                            }
                        ]}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            // 月份筛选
            $('#year-month-filter').on('change', function() {
                var yearMonth = $(this).val();
                window.location.href = 'hr/attendance/index?year_month=' + yearMonth;
            });
        },
        monthly: function () {
            console.log('HR Attendance Monthly - Init Start');
            
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'hr/attendance/monthly' + location.search,
                    table: 'hr_attendance_monthly',
                }
            });

            var table = $("#table");
            console.log('Table element found:', table.length > 0);

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('ID'), sortable: true},
                        {field: 'user_name', title: __('员工姓名')},
                        {field: 'year_month', title: __('年月'), sortable: true},
                        {field: 'actual_days', title: __('实际出勤天数')},
                        {field: 'normal_days', title: __('正常天数')},
                        {field: 'late_days', title: __('迟到天数')},
                        {field: 'early_leave_days', title: __('早退天数')},
                        {field: 'total_work_hours', title: __('总工作时长')},
                        {field: 'overtime_hours', title: __('加班时长')}
                    ]
                ],
                onLoadSuccess: function(data) {
                    console.log('Table loaded successfully:', data);
                },
                onLoadError: function(status, res) {
                    console.error('Table load error:', status, res);
                }
            });

            console.log('Bootstrap Table initialized');

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            // 月份筛选
            $('#year-month-filter').on('change', function() {
                var yearMonth = $(this).val();
                window.location.href = 'hr/attendance/monthly?year_month=' + yearMonth;
            });
            
            console.log('HR Attendance Monthly - Init Complete');
        },
        statistics: function () {
            // ECharts趋势图
            require(['echarts'], function(echarts) {
                var chartDom = document.getElementById('attendance-trend-chart');
                var myChart = echarts.init(chartDom);
                
                var option = {
                    title: {
                        text: '出勤趋势'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    xAxis: {
                        type: 'category',
                        data: trendData.dates
                    },
                    yAxis: {
                        type: 'value',
                        name: '出勤人次'
                    },
                    series: [{
                        name: '出勤人次',
                        type: 'line',
                        smooth: true,
                        data: trendData.counts,
                        itemStyle: {
                            color: '#5cb85c'
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0, color: 'rgba(92, 184, 92, 0.5)'
                                }, {
                                    offset: 1, color: 'rgba(92, 184, 92, 0.1)'
                                }]
                            }
                        }
                    }]
                };
                
                myChart.setOption(option);
                
                // 响应式
                window.addEventListener('resize', function() {
                    myChart.resize();
                });
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
